﻿using System.Diagnostics;
using System.Text;
using Castle.Core.Internal;
using Castle.DynamicProxy;

namespace Net12_AOP
{
    internal class RemoteClientProxy : StandardInterceptor
    {
        private readonly Stopwatch _sw = new Stopwatch();

        protected override void PreProceed(IInvocation invocation)
        {
            _sw.Start();
        }

        protected override void PerformProceed(IInvocation invocation)
        {
            var ma = invocation.Method.GetAttribute<RemoteCallMethodAttribute>();
            if (ma == null)
            {
                Console.WriteLine($"method {invocation.Method.Name} is not correct for remote call");
                return;
            }

            var argList = invocation.Arguments;
            var pList = invocation.Method.GetParameters();
            var url = ma.Url;
            for (var i = 0; i < pList.Length; ++i)
            {
                var name = pList[i];
                url = url.Replace($"#{name.Name}", $"{argList[i]}");
            }

            // 简单模拟，假设Url不为空
            HttpClient client = new HttpClient();
            var sw = new Stopwatch();
            sw.Start();
            if (ma.Method == CallMethod.Get)
            {
                invocation.ReturnValue = client.GetStringAsync(url).Result;
            }
            else
            {
                invocation.ReturnValue =
                    client.PostAsync(url, new StringContent("", Encoding.UTF8, "application/json"));
            }

            sw.Stop();
            Console.WriteLine($"use {sw.ElapsedMilliseconds}ms for remote call");
        }

        protected override void PostProceed(IInvocation invocation)
        {
            _sw.Stop();
            Console.WriteLine($"this remote call({invocation.Method.Name}) used {_sw.ElapsedMilliseconds}ms");
        }
    }
}